package com.vanke.devops.domain.manager.docker.impl;

import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.api.model.Statistics;
import com.vanke.core.util.JsonUtil;
import com.vanke.devops.domain.job.ContainerMonitorJob;
import com.vanke.devops.domain.manager.docker.bean.ContainerInfo;
import com.vanke.devops.domain.manager.docker.bean.Cpu;
import com.vanke.devops.domain.manager.docker.bean.Memory;

import java.io.Closeable;
import java.io.IOException;

/**
 * @author 陈景阳
 * @since 2018/6/6
 */
public class ResultCallbackStatisticsImpl implements ResultCallback<Statistics> {

    private ContainerMonitorJob containerMonitorJob;

    private Container container;

    private String ip;


    public ResultCallbackStatisticsImpl(ContainerMonitorJob containerMonitorJob, Container container, String ip) {
        this.containerMonitorJob = containerMonitorJob;
        this.container = container;
        this.ip = ip;
    }

    @Override
    public void onStart(Closeable closeable) {

    }

    @Override
    public void onNext(Statistics object) {
        String jsonMemory = JsonUtil.toJson(object.getMemoryStats());
        Memory memory = JsonUtil.fromJson(jsonMemory,Memory.class);

        String jsonCpu = JsonUtil.toJson(object.getCpuStats());
        Cpu cpu = JsonUtil.fromJson(jsonCpu,Cpu.class);

        ContainerInfo containerInfo = new ContainerInfo(container.getId(),ip,container.getNames()[0]);
        containerInfo.setCpu(cpu);
        containerInfo.setMemory(memory);


        containerMonitorJob.offer(containerInfo);

        try {
            //2秒查询一次
            Thread.sleep(2 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //抛异常是为了停止线程
        throw new RuntimeException();
    }

    @Override
    public void onError(Throwable throwable) {
        //抛异常是为了停止线程
        throw new RuntimeException();
    }

    @Override
    public void onComplete() {

    }

    @Override
    public void close() throws IOException {

    }
}
